package io.renren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.google.gson.internal.$Gson$Preconditions;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.Result;
import io.renren.dao.FinanceDao;
import io.renren.dto.*;
import io.renren.entity.FinanceEntity;
import io.renren.entity.UserEntity;
import io.renren.service.*;
import io.renren.utils.StringsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 财务记录表
 *
 * @author 翟文闯 619556390@QQ.com
 * @since 1.0.0 2019-12-04
 */
@Service
public class FinanceServiceImpl extends CrudServiceImpl<FinanceDao, FinanceEntity, FinanceDTO> implements FinanceService {

    @Autowired
    private FinanceDao financeDao;
    @Autowired
    private  FinanceService financeService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysDeptService sysDeptService;
    @Override
    public QueryWrapper<FinanceEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<FinanceEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }
    /**
     * 根据状态0未结算 或者1已结算 查询订单  创建人，审核人，并关联出 名字
     * @param dto
     * @return
     */
    @Override
    public HashMap<String, Object> selectFinance(FinanceDTO dto) {
        String isPayment ="";
        String supplierId ="";
        String bgeinDate = "";
        String endDate = "";
        if("" != dto.getBgeinDate()){
            bgeinDate =" and  DATE_FORMAT('"+dto.getBgeinDate()+"','%Y-%m-%d') <= DATE_FORMAT(m.create_date,'%Y-%m-%d') ";
        }
        if("" != dto.getEndDate()){
            endDate =" and  DATE_FORMAT('"+dto.getEndDate()+"','%Y-%m-%d') >= DATE_FORMAT(m.create_date,'%Y-%m-%d') ";
        }
        if(0== dto.getIsPayment()){
            isPayment = "  and  is_payment = 0 ";
        }else {
            isPayment = "  and  is_payment != 0 ";
        }
        if(null!=dto.getSupplierId()){
            supplierId =" and supplier_id =" + dto.getSupplierId();
        }
        //根据订单类型判断是哪个食堂进货，通过唯一订单号获取创建时间，创建人，审核人，并关联出 名字
        List<FinanceDTO> list = financeDao.selectFinance(isPayment,supplierId,bgeinDate,endDate);
        HashMap<String, Object> map = new HashMap<>();
        if(list.size() > 0) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String firstDate= formatter.format(list.get(0).getCreateDate());
            int size = list.size()-1;
            String lastDate = formatter.format(list.get(size).getCreateDate());
            map.put("firstDate",firstDate);
            map.put("lastDate",lastDate);
        }else {
            map.put("firstDate",dto.getBgeinDate());
            map.put("lastDate",dto.getEndDate());
        }
        FinanceDTO financeDTO1 = financeDao.getFinance1(0,supplierId);
        FinanceDTO financeDTO2 = financeDao.getFinance(0,supplierId,bgeinDate,endDate);
      if(null !=financeDTO1){
          map.put("ntotalNum",financeDTO1.getTotalNum());
      }else {
          map.put("ntotalNum",0);
      }
      if(null !=financeDTO2){
          map.put("ytotalNum",financeDTO2.getTotalNum());;
      }else {
          map.put("ytotalNum",0);
      }


        ArrayList<FinanceDTO>  financemxList= new ArrayList<>();
        if(list.size() > 0) {
            for (FinanceDTO financeDTO : list) {
                String deptName = sysDeptService.getDeptName(Long.parseLong(financeDTO.getCanteenId())).getName();

                if ("1".equals(financeDTO.getType())) {
                    FinancemxDTO stockOrder = financeDao.getStockOrder(financeDTO.getOrderid());//,bgeinDate,endDate, dto.getSupplierId()
                    if(null!=stockOrder){
                        deptName = deptName+"每日进货清单";
                        financeDTO.setChedId(stockOrder.getChedId());
                        financeDTO.setCanteenAdminId(stockOrder.getCanteenAdminId());
                        financeDTO.setCreateDate(stockOrder.getCreateDate());
                        financeDTO.setAuditTime(stockOrder.getAuditTime());
                        financeDTO.setDeptName(deptName);
                        financeDTO.setSupplierName(stockOrder.getSupplierName());
                        SysRoleDTO sysRoleDTO1 = sysRoleService.getRoleName(stockOrder.getChedId()).get(0);
                        financeDTO.setChedName(sysRoleDTO1.getName()+"  "+stockOrder.getChedName());
                        SysRoleDTO sysRoleDTO = sysRoleService.getRoleName(stockOrder.getChedId()).get(0);
                        financeDTO.setCanteenAdminName(sysRoleDTO.getName()+"  "+stockOrder.getCanteenAdminName());
                    }

                } else if ("2".equals(financeDTO.getType())) {
                    FinancemxDTO auxiliaryOrder = financeDao.getAuxiliaryOrder(financeDTO.getOrderid());//,bgeinDate,endDate, dto.getSupplierId()
                    if (null != auxiliaryOrder) {
                        deptName = deptName+"辅材采购清单";
                        financeDTO.setChedId(auxiliaryOrder.getChedId());
                        financeDTO.setCanteenAdminId(auxiliaryOrder.getCanteenAdminId());
                        financeDTO.setDeptName(deptName);
                        financeDTO.setCreateDate(auxiliaryOrder.getCreateDate());
                        financeDTO.setAuditTime(auxiliaryOrder.getAuditTime());
                        financeDTO.setSupplierName(auxiliaryOrder.getFoodName());
                        SysRoleDTO sysRoleDTO1 = sysRoleService.getRoleName(auxiliaryOrder.getChedId()).get(0);
                        financeDTO.setChedName(sysRoleDTO1.getName()+"  "+auxiliaryOrder.getChedName());
                        SysRoleDTO sysRoleDTO = sysRoleService.getRoleName(auxiliaryOrder.getCanteenAdminId()).get(0);
                        financeDTO.setCanteenAdminName(sysRoleDTO.getName()+"  "+auxiliaryOrder.getCanteenAdminName());
                    }
                } else if("3".equals(financeDTO.getType())){
                    FinancemxDTO smallCanteenOrder = financeDao.getsmallCanteenOrder(financeDTO.getOrderid());//,bgeinDate,endDate, dto.getSupplierId()
                    if (null != smallCanteenOrder) {
                        deptName = StringsUtils.getCanteenName(deptName)+"食堂进货清单";
                        financeDTO.setChedId(smallCanteenOrder.getChedId());
                        financeDTO.setCanteenAdminId(smallCanteenOrder.getCanteenAdminId());
                        financeDTO.setDeptName(deptName);
                        financeDTO.setCreateDate(smallCanteenOrder.getCreateDate());
                        financeDTO.setAuditTime(smallCanteenOrder.getAuditTime());
                        financeDTO.setSupplierName(smallCanteenOrder.getSupplierName());
                        financeDTO.setBoxId(smallCanteenOrder.getBoxId());
                        SysRoleDTO sysRoleDTO1 = sysRoleService.getRoleName(smallCanteenOrder.getChedId()).get(0);
                        financeDTO.setChedName(sysRoleDTO1.getName()+"  "+smallCanteenOrder.getChedName());
                        SysRoleDTO sysRoleDTO = sysRoleService.getRoleName(smallCanteenOrder.getCanteenAdminId()).get(0);
                        financeDTO.setCanteenAdminName(sysRoleDTO.getName()+"  "+smallCanteenOrder.getCanteenAdminName());
                    }
                }
                financemxList.add(financeDTO);

            }
        }
        map.put("financemxList",financemxList);
        return map;
    }

    /**
     *
     * 根据状态0未结算 或者1已结算 查询订单详情商品名，单价，数量，单位
     * @param dto 类型 订单 供应商id
     * @return
     */
    @Override
    public List<FinancemxDTO> selectFinancemx(FinanceDTO dto) {
        List<FinancemxDTO> financemxDTOList;
        Long supplierId = dto.getSupplierId();
        Long orderid = dto.getOrderid();
        String type = dto.getType();
        if("1".equals(type)){
            financemxDTOList = financeDao.getStockmxOrder(supplierId, orderid);
        }else if("2".equals(type)){
            financemxDTOList = financeDao.getAuxiliarymxOrder(supplierId, orderid);
        }else if("3".equals(type)){
             financemxDTOList = financeDao.getsmallCanteenmxOrder(supplierId, orderid);
        }else {
            financemxDTOList = financeDao.getBatchMxOrder(supplierId, orderid);
        }
        return financemxDTOList;
    }




    @Override
    public List<FinanceDTO> selectSupplierFinance(FinanceDTO dto) {

        String isPayment;
        String types;
        if(0== dto.getIsPayment()){
           isPayment = "  and  fe.`is_payment` = 0 ";
        }else {
            isPayment = "  and  fe.`is_payment` != 0 ";
        }
        if("4".equals(dto.getType())){
            types = "  and  fe.`type` = 4 ";
        }else {
            types = "  and  fe.`type` != 4 ";
        }
        List<FinanceDTO> list = financeDao.selectSupplierFinance(isPayment,types);
        return list;
    }

    @Override
    public FinanceDTO selectTotalFinance() {
        FinanceDTO financeDTO = new FinanceDTO();
        financeDTO.setTotalNum( financeDao.select1Finance().getTotalNum());
        financeDTO.setYtotalNum( financeDao.select2Finance().getYtotalNum());
        financeDTO.setNtotalNum(financeDao.select3Finance().getNtotalNum());
        return financeDTO;
    }

    @Override
    public Result updateExamine(FinancemxDTO dto, UserEntity userEntity) {
        String financeIds = dto.getFinanceIds();
        String[] arr = financeIds.split(","); // 用,分割
        for (String financeId : arr) {
            FinanceDTO financeDTO = financeDao.selectActualAmount(Long.parseLong(financeId));
            financeDTO.setActualAmountPaid(financeDTO.getAmountPayable());
            financeDTO.setIsPayment(dto.getIsPayment());
            financeDTO.setOperatorTime(new Date()+"");
            financeDTO.setOperator(userEntity.getDeptName());
            financeDTO.setActualAmountPaid(financeDTO.getActualAmountPaid());
            financeDTO.setFinanceId(Long.parseLong(financeId));
            update(financeDTO);
            if("4".equals(dto.getType())){
                FinanceDTO dto1 = financeService.get(Long.parseLong(financeId));
                financeDao.update1(dto1.getOrderid());
                System.out.println("翟文闯");
            }
        }
        return new Result();
    }

    /**
     * 统计报表 库存表，入库表， 出库表 ，结余数据
     * @return
     */
    @Override
    public List<FinanceStatementDTO> selectFinanceStatement() {
        List<FinanceStatementDTO> list = new ArrayList<>();
        List<FinanceStatementDTO> foodmxList = financeDao.selectfoodmx();//库存表所有商品的数量及价格
        List<FinanceStatementDTO> collarList = financeDao.selectcollar();//本月辅材领取的数量及价格
        List<FinanceStatementDTO> auxiliaryList = financeDao.selectauxiliary();//本月辅材入库表中的价格及数量
        for (FinanceStatementDTO financeStatementDTO:foodmxList) {
            for (FinanceStatementDTO financeDTO:collarList) {
                if(financeStatementDTO.getFoodId().equals(financeDTO.getFoodId())){
                  financeStatementDTO.setGetTotalNum2(financeDTO.getGetTotalNum2());
                  financeStatementDTO.setGetTotalPrice2(financeDTO.getGetTotalPrice2());
              }
            }
            for (FinanceStatementDTO statementDTO:auxiliaryList) {
                if(financeStatementDTO.getFoodId().equals(statementDTO.getFoodId())){
                    financeStatementDTO.setPutArrivalNum(statementDTO.getPutArrivalNum());
                    financeStatementDTO.setPutTotalprice(statementDTO.getPutTotalprice());
                }
            }
            list.add(financeStatementDTO);

        }
        //上个月结余 == 当前库存+出库-入库
            for (FinanceStatementDTO statementDTO:list) {
              float  foodmxTotalprice = 0F;
              float  putTotalprice = 0F;
              float  getTotalPrice2 = 0F;
              float  surplusPrice =0F ;
              float  foodmxArrivalNum = 0F;
              float  putArrivalNum = 0F;
              float  getTotalNum2 = 0F;
              float  surplusNum =0F;
              if(null!= statementDTO.getFoodmxTotalprice()){
                  foodmxTotalprice =  statementDTO.getFoodmxTotalprice();
              }
              if(null != statementDTO.getPutTotalprice()) {
                  putTotalprice= statementDTO.getPutTotalprice();
              }
              if(null != statementDTO.getGetTotalPrice2()) {
                  getTotalPrice2= statementDTO.getGetTotalPrice2();
              }
                surplusPrice = foodmxTotalprice + putTotalprice - getTotalPrice2;//运算操作
                statementDTO.setSurplusPrice(surplusPrice);
              if(null != statementDTO.getFoodmxArrivalNum()){
                  foodmxArrivalNum = statementDTO.getFoodmxArrivalNum();
              }
              if(null != statementDTO.getPutArrivalNum()){
                  putArrivalNum = statementDTO.getPutArrivalNum();
              }
              if(null != statementDTO.getGetTotalNum2()){
                  getTotalNum2 = statementDTO.getGetTotalNum2();
              }
                surplusNum = foodmxArrivalNum + putArrivalNum - getTotalNum2;
               statementDTO.setSurplusNum( surplusNum);//运算操作
            }
        return list;
    }
    @Override
    public List<FinanceDTO> getBatchOrder(FinanceDTO dto){
        String canteenId ="";
        if(StringUtils.isNotBlank(dto.getCanteenId())){
          canteenId = " and A.canteen_id = " + dto.getCanteenId();
        }
        List<FinanceDTO> batchOrder = financeDao.getBatchOrder(canteenId);
        return batchOrder;
    }

    @Override
    public Map getBatchOrderMx(FinanceDTO dto) {
        HashMap<Object, Object> map = new HashMap<>();
        List<BatchOrdermxDTO> batchOrdermx = financeDao.getBatchOrdermx(dto.getOrderid());
        BatchOrderDTO batchOrderDTO = financeDao.getTotalMoney(dto.getOrderid());
        Float tatolMoney = batchOrderDTO.getTatolMoney();
        map.put("batchOrderDTO",batchOrderDTO);
        map.put("batchOrdermx",batchOrdermx);
        map.put("tatolMoney",tatolMoney);
        System.out.println(map);
        return map;
    }

}